#include "text.h"
#include "base.h"
#include <fstream>
using namespace std;

TextMap::TextMap(): language(""), data(){}

wchar_t* ANSIToUnicode(const char* str)
{
     int textlen ;
     wchar_t * result;
     textlen = MultiByteToWideChar( CP_ACP, 0, str,-1, NULL,0 );
     result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));
     memset(result,0,(textlen+1)*sizeof(wchar_t));
     MultiByteToWideChar(CP_ACP, 0,str,-1,(LPWSTR)result,textlen );
     return result;
}

Ogre::String Base::get_text(Ogre::String key)
{
	return text_map.get(key);
}


Ogre::DisplayString Base::get_UTFtext(Ogre::String key)
{
	return ANSIToUnicode(get_text(key).c_str());
}

void TextMap::init()
{
	Ogre::ConfigFile cf;
	cf.load(TEXT_FILE_NAME);
	Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
	Ogre::String sec, key, value;
	while (seci.hasMoreElements())
	{
		sec = seci.peekNextKey();
		//MessageBox(NULL, sec.c_str(), "test", MB_OK);
		Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
		Ogre::ConfigFile::SettingsMultiMap::iterator i;
		for (i = settings->begin(); i != settings->end(); ++i)
		{
			key = i->first;
			value = i->second;

			//MessageBox(NULL, (sec+"-"+key+"-"+value).c_str(), "key", MB_OK);
			if (sec == "" && key == "language")
			{
				language = value;
			}
			else
			{
				insert(sec + ":" + key, value);
			}
		}
	}
	return;
}

Ogre::String TextMap::get(Ogre::String key)
{
	if (language == "")
		return "Error";
	key = language + ":" + key;
	if (!data.count(key))
		throw Ogre::Exception(1, "Unable to get text map <" + key + "> ", "text.cpp, TextMap::get");
	else
		return data[key];
}

void TextMap::insert(Ogre::String key, Ogre::String value)
{
	if (data.count(key))
		throw Ogre::Exception(1, "Duplicated text map <" + key + "> to \"" + data[key] + "\" and \"" + value + "\" ", "text.cpp, TextMap::insert");
	else
		data[key] = value;
}

// copied code to prepare TTF texture

int generateFontTexture(Ogre::String fontName, bool load=false)
{
    Ogre::FontPtr font = Ogre::FontManager::getSingleton().getByName(fontName);
    if(font.isNull()) return 1;
 
    if(font->getType() != Ogre::FT_TRUETYPE)
        return 1;
 
    if(!font->isLoaded())
        font->load();
 
    Ogre::String texname = font->getMaterial()->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getTextureName();
 
 
    Ogre::TexturePtr fontTexture = Ogre::TextureManager::getSingleton().getByName(texname);
    Ogre::HardwarePixelBufferSharedPtr fontBuffer = fontTexture->getBuffer();
 
    if(fontBuffer.isNull())
        return 1;
 
    // create a remporary buffer that holds the font
    size_t nBuffSize = fontBuffer->getSizeInBytes();
    Ogre::uint8* buffer = (Ogre::uint8*)calloc(nBuffSize, sizeof(Ogre::uint8)); 
    Ogre::PixelBox fontPb(fontBuffer->getWidth(), fontBuffer->getHeight(),fontBuffer->getDepth(), fontBuffer->getFormat(), buffer);          
    fontBuffer->blitToMemory(fontPb);
 

    return 0;
}
 
// if you want to use this, use instead of the original texture name, the texture name plus cache_name (see top)
// this function creates the font cache if its not existing
int fontCacheInit(Ogre::String fontName)
{
    Ogre::FontPtr font_org = Ogre::FontManager::getSingleton().getByName(fontName);
    Ogre::FontPtr font_cache = Ogre::FontManager::getSingleton().getByName(fontName + "_cached");
 
    // base font not even existing?
    if(font_org.isNull()) return 1;
    // using texture fonts is a bit stupid ...
    if(font_org->getType() != Ogre::FT_TRUETYPE) return 1;
 
    int res = 0;
    if(font_cache.isNull())
        res = generateFontTexture(fontName);
 
    if(font_org->isLoaded()) font_org->unload();
    return res;
}
 
int generateAllFontTextures()
{
    Ogre::ResourceManager::ResourceMapIterator itf2 = Ogre::FontManager::getSingleton().getResourceIterator();
    while (itf2.hasMoreElements())
        generateFontTexture(itf2.getNext()->getName());
 
    Ogre::LogManager::getSingleton().logMessage("all font textures generated");
    return 0;
}

//end
